﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using Lib.Web.Mvc;

namespace jQuery.UI.Progressbar.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        #region Actions
        public ActionResult Progressbar()
        {
            Session["OPERATION_PROGRESS"] = 0;
            return View();
        }

        /// <summary>
        /// Action for triggering long running operation
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Operation()
        {
            HttpSessionStateBase session = Session;

            //Separate thread for long runnig operation
            ThreadPool.QueueUserWorkItem(delegate
            {
                int operationProgress;
                for (operationProgress = 0; operationProgress <= 100; operationProgress = operationProgress + 2)
                {
                    session["OPERATION_PROGRESS"] = operationProgress;
                    Thread.Sleep(1000);
                }
            });

            return Json(new { progress = 0 });
        }

        /// <summary>
        /// Action for reporting operation progress
        /// </summary>
        /// <returns></returns>
        [NoCache]
        public ActionResult OperationProgress()
        {
            int operationProgress = 0;

            if (Session["OPERATION_PROGRESS"] != null)
                operationProgress = (int)Session["OPERATION_PROGRESS"];

            return Json(new { progress = operationProgress }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
